package com.quectel.cms.controller.forum;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.forum.ForumTopicBusiness;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.forum.dto.ForumTopicBindingDto;
import com.quectel.core.module.forum.dto.ForumTopicDto;
import com.quectel.core.module.forum.service.ForumTopicBindingService;
import com.quectel.core.module.forum.service.ForumTopicService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/10 11:21
 */
@RestController
@RequestMapping("forumTopic")
@Tag(name = "ForumTopicController", description = "邻友圈话题管理相关api")
public class ForumTopicController extends BaseController {

    @DubboReference
    private ForumTopicService forumTopicService;
    @DubboReference
    private ForumTopicBindingService forumTopicBindingService;
    @DubboReference
    private VillageService villageService;

    @Autowired
    private ForumTopicBusiness forumTopicBusiness;


    /**
     * 查询全部的话题
     *
     * @return
     */
    @GetMapping("queryAll")
    @Operation(summary = "获取邻友圈话题管理列表")
    public Response<List<ForumTopicDto>> queryAll(
            @Parameter(description = "1小区2城市3全国") @RequestParam Byte queryRange,
            @Parameter(description = "城市code") @RequestParam(required = false) String cityCode,
            @Parameter(description = "小区id") @RequestParam(required = false) Long villageId,
            @Parameter(description = "话题类型") @RequestParam(required = false) Byte category
    ) {
        //查询列表数据
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        //topic的一些限制
        HashMap<String, Object> topicParams = new HashMap<>(2);
        topicParams.put(LambdaUtil.getFieldName(ForumTopicDto::getStatus), String.valueOf(SystemConstants.NORMAL));
        if (category != null) {
            topicParams.put(LambdaUtil.getFieldName(ForumTopicDto::getCategory), String.valueOf(category));
        }

        List<ForumTopicDto> forumTopicDtos = new ArrayList<>();
        //根据不同的范围查询topicList
        if (ForumConstants.ForumRange.VILLAGE.getRange().equals(queryRange)) {
            if (villageId == null) {
                return Response.<List<ForumTopicDto>>ok().wrap(null);
            }
            VillageDto villageDto = villageService.selectCacheById(villageId);
            if (villageDto == null) {
                return Response.error("无法查询到小区信息，请联系管理员");
            }
            forumTopicDtos = forumTopicBusiness.getVillageTopic(Collections.singletonList(villageDto.getId()), topicParams);
        } else if (ForumConstants.ForumRange.CITY.getRange().equals(queryRange)) {
            forumTopicDtos = forumTopicBusiness.getCityTopic(SessionHolder.getSysUser().getTenantId(), cityCode, topicParams);
        } else if (ForumConstants.ForumRange.ALL.getRange().equals(queryRange)) {
            forumTopicDtos = forumTopicBusiness.getAll(SessionHolder.getSysUser().getTenantId(), topicParams);
        }

        return Response.<List<ForumTopicDto>>ok().wrap(forumTopicDtos);
    }


    /**
     * 修改状态
     *
     * @param forumTopicDto
     * @return
     */
    @PostMapping("updateStatus")
    @RequirePermissions(values = "forumTopic:close")
    @Operation(summary = "修改状态")
    public Response<Object> updateStatus(@RequestBody ForumTopicDto forumTopicDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(forumTopicDto.getId()));
        if (forumTopicService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        //填充基础数据
        fillEditCommonData(forumTopicDto);

        forumTopicService.updateById(forumTopicDto);

        return Response.ok();
    }

    /**
     * 查询绑定的小区
     */
    @GetMapping("queryBindVillages")
    public Response<List<VillageDto>> queryBindVillages(@RequestParam Long forumId) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        Map<String, Object> params = request.getParams();
        params.put(LambdaUtil.getFieldName(ForumTopicBindingDto::getForumTopicId), forumId);
        List<ForumTopicBindingDto> forumTopicBindingDtos = forumTopicBindingService.queryList(params);
        List<VillageDto> result = null;
        if (CollectionUtils.isNotEmpty(forumTopicBindingDtos)) {
            for (ForumTopicBindingDto bindingDto : forumTopicBindingDtos) {
                VillageDto villageDto = villageService.selectCacheById(bindingDto.getVillageId());
                if (villageDto != null) {
                    result.add(villageDto);
                }
            }
        }
        return Response.<List<VillageDto>>ok().wrap(result);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "forumTopic:list")
    @Operation(summary = "分页获取邻友圈话题管理列表")
    public Response<Page<ForumTopicDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = forumTopicService.queryTotal(request.getParams());

        List<ForumTopicDto> list = null;
        if (total > 0) {
            list = forumTopicService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ForumTopicDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ForumTopicDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "forumTopic:edit")
    @Operation(summary = "在编辑时根据id查询邻友圈话题管理详情")
    public Response<ForumTopicDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumTopicService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumTopicDto forumTopicDto = forumTopicService.selectById(id);
        List<VillageDto> villageDtoList = forumTopicBindingService.selectByForumId(forumTopicDto.getId());
        forumTopicDto.setVillageDtoList(villageDtoList);

        return Response.<ForumTopicDto>ok().wrap(forumTopicDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "forumTopic:info")
    @Operation(summary = "根据id查询邻友圈话题管理的详情")
    public Response<ForumTopicDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumTopicService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumTopicDto forumTopicDto = forumTopicService.selectById(id);

        return Response.<ForumTopicDto>ok().wrap(forumTopicDto);
    }

    /**
     * 保存
     *
     * @param forumTopicDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "forumTopic:edit")
    @Operation(summary = "新增邻友圈话题管理")
    public Response<Object> save(@RequestBody @Validated ForumTopicDto forumTopicDto) {

        //填充基础数据
        fillSaveCommonData(forumTopicDto);

        forumTopicService.saveOrUpdate(forumTopicDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param forumTopicDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "forumTopic:edit")
    @Operation(summary = "根据id修改邻友圈话题管理")
    public Response<Object> update(@RequestBody @Validated ForumTopicDto forumTopicDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(forumTopicDto.getId()));
        if (forumTopicService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(forumTopicDto);

        forumTopicService.saveOrUpdate(forumTopicDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "forumTopic:delete")
    @Operation(summary = "根据多条记录id批量删除邻友圈话题管理")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (forumTopicService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        forumTopicService.deleteBatch(ids);

        return Response.ok();
    }
}
